package com.scgk.sync.common.utils;

import com.alibaba.fastjson.JSONArray;
import com.jcraft.jsch.*;
import com.scgk.sync.common.ErrorType;
import com.scgk.sync.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.util.*;

@Slf4j
public class SftpClientUtil {

    private Session session;
    private Channel channel;
    private ChannelSftp sftp;
    private InputStream in;
    private OutputStream out;

    /**
     * 构造函数1
     *
     * @param host       主机
     * @param username   用户名
     * @param password   密码
     * @param port       端口
     * @param isHightSSH :jsch 与 ssh 版本适配，ssh>7.6 为true,反之为false
     * @throws Exception
     */
    public SftpClientUtil(String host, String username, String password, int port, boolean isHightSSH) throws Exception {
        JSch jsch = new JSch();
        this.session = jsch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey
        if (isHightSSH) {
            config.put("kex", "diffie-hellman-group1-sha1,"
                    + "diffie-hellman-group-exchange-sha1,"
                    + "diffie-hellman-group-exchange-sha256"); //适配新版本ssh需添加对应的加密算法
        }
        session.setConfig(config);
        try {
            session.connect();
        } catch (Exception e) {
            if (session.isConnected())
                session.disconnect();
            log.error("链接报错!!!", e);
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        channel = session.openChannel("sftp");
        try {
            if (channel.isConnected())
                channel.disconnect();
            channel.connect();
        } catch (Exception e) {
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        sftp = (ChannelSftp) channel;
    }

    /**
     * 构造函数2
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @param encoding 字符集编码
     * @throws Exception
     */
    public SftpClientUtil(String host, String username, String password, int port, String encoding) throws Exception {
        JSch jsch = new JSch();
        this.session = jsch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey
        session.setConfig(config);
        try {
            session.connect();
        } catch (Exception e) {
            if (session.isConnected())
                session.disconnect();
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],端口[" + port + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        channel = session.openChannel("sftp");
        try {
            channel.connect();
        } catch (Exception e) {
            if (channel.isConnected())
                channel.disconnect();
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],密码[" + password + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        sftp = (ChannelSftp) channel;
        sftp.setFilenameEncoding(encoding);
    }

    /**
     * 构造函数3
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @param encoding 字符集
     * @param timeout  超时时间
     * @throws Exception
     */
    private SftpClientUtil(String host, String username, String password, int port, String encoding, int timeout)
            throws Exception {
        JSch jsch = new JSch();
        this.session = jsch.getSession(username, host, port);
        session.setPassword(password);
        Properties config = new Properties();
        config.put("StrictHostKeyChecking", "no"); // 不验证 HostKey
        session.setConfig(config);
        try {
            session.connect();
        } catch (Exception e) {
            if (session.isConnected())
                session.disconnect();
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],密码[" + password + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        session.setTimeout(timeout);
        channel = session.openChannel("sftp");
        try {
            channel.connect();
        } catch (Exception e) {
            if (channel.isConnected())
                channel.disconnect();
            throw new Exception("连接服务器失败,请检查主机[" + host + "],端口[" + port + "],用户名[" + username + "],密码[" + password + "]是否正确,以上信息正确的情况下请检查网络连接是否正常或者请求被防火墙拒绝.");
        }
        sftp = (ChannelSftp) channel;
        sftp.setFilenameEncoding(encoding);
    }

    /**
     * 文件上传
     *
     * @param remotePath     远端路径
     * @param remoteFileName 上传到远端后的文件名
     * @param localPath      本地路径
     * @param localFileName  本地文件名
     * @return
     */
    public boolean uploadFile(String remotePath, String remoteFileName, String localPath, String localFileName) {
        FileInputStream in = null;
        try {
            createDir(remotePath);
            File file = new File(localPath + localFileName);
            in = new FileInputStream(file);
            sftp.put(in, remoteFileName);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (SftpException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return false;
    }

    //创建目录
    public boolean createDir(String createpath) {
        try {
            createpath = createpath.trim();
            if (isDirExist(createpath)) {
                this.sftp.cd(createpath);
                log.info("cd " + createpath);
                return true;
            }
            String[] pathArray = createpath.split("/");
            for (String path : pathArray) {
                path = path.trim();
                if ("".equals(path)) {
                    continue;
                }
                if (!isDirExist(path)) {
                    sftp.mkdir(path);
                }
                log.info("cd " + path);
                sftp.cd(path);
            }
            return true;
        } catch (SftpException e) {
            e.printStackTrace();
        }
        return false;
    }

    //判断目录是否存在
    public boolean isDirExist(String directory) {
        boolean isDirExistFlag = false;
        try {
            SftpATTRS sftpATTRS = sftp.lstat(directory);
            return sftpATTRS.isDir();
        } catch (Exception e) {
            if (e.getMessage().toLowerCase().equals("no such file")) {
                log.error("directory：" + directory + ",no such file ERROR!!！");
            }
        }
        return isDirExistFlag;
    }

    /**
     * 文件下载--从sftp服务器上下载文件
     *
     * @param remotePath 远程文件存放路径  /：代表sftp设置的根目录
     * @param localPath  下载到本地的路径
     * @return 下载后的文件名集合
     * @throws Exception
     */
    public List<String> downloadFiles(String remotePath, String localPath) {
        List<String> downloadFiles = new ArrayList<String>();

        try {
            log.info("切换到指定目录：" + remotePath);
            boolean flag = openDir(remotePath, sftp);
            if (flag) {
                //1.获取远端路径下所有文件
                Vector<?> vv = listFiles("*");
                if (vv == null) {
                    return null;
                } else {
                    for (Object object : vv) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                        String remoteFileName = entry.getFilename();

                        log.info("校验文件名：" + remoteFileName);
                        String path = localPath.substring(localPath.length() - 1).equals("/") ? localPath : localPath + "/";
                        File file = new File(path + remoteFileName);
                        log.info("保存校对文件的本地路径为:" + file.getAbsolutePath());

                        log.info("start downLoad " + remoteFileName + " ~~");
                        sftp.get(remoteFileName, new FileOutputStream(file));
                        log.info("downLoad ok ~~");

                        downloadFiles.add(remoteFileName);
                    }

                    if (downloadFiles.size() < 1) {
                        log.error("remotePath：" + remotePath + "路径下，未匹配到校对文件！");
                    }
                }
            } else {
                log.info("对应的目录" + remotePath + "不存在！");
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                }
            }
            if (session != null) {
                if (session.isConnected()) {
                    session.disconnect();
                }
            }
        }
        return downloadFiles;
    }

    /**
     * 文件下载--从sftp服务器上下载文件
     *
     * @param remotePath 远程文件存放路径  /：代表sftp设置的根目录
     * @param localPath  下载到本地的路径
     * @return 下载后的文件名集合
     * @throws Exception
     */
    public List<String> downloadFilesInputStream(String remotePath, String localPath) {
        List<String> downloadFiles = new ArrayList<String>();
        try {
            boolean flag = openDir(remotePath, sftp);
            if (flag) {
                //获取远端路径下所有文件
                Vector<?> vv = listFiles("*");
                if (vv == null) {
                    return null;
                } else {
                    for (Object object : vv) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                        String remoteFileName = entry.getFilename();
                        String path = localPath.substring(localPath.length() - 1).equals("/") ? localPath : localPath + "/";
                        File file = new File(path + remoteFileName);

                        //远程文件存放路径
                        InputStream inputStream = sftp.get(remotePath + remoteFileName);
                        FileUtils.copyInputStreamToFile(inputStream, file);

                        downloadFiles.add(remoteFileName);

                        inputStream.close();
                    }

                    if (downloadFiles.size() < 1) {
                        log.error("远程文件存放：" + remotePath + "路径下，未匹配到校对文件！");
                    }
                }

            } else {
                log.info("对应的远程文件存放路径" + remotePath + "不存在！");
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                }
            }
            if (session != null) {
                if (session.isConnected()) {
                    session.disconnect();
                }
            }
        }
        return downloadFiles;
    }


    /**
     * 文件下载--从sftp服务器上下载文件
     *
     * @param remotePath 远程文件存放路径  /：代表sftp设置的根目录
     * @param localPath  下载到本地的路径
     * @return 文件当中的数据集合
     * @throws Exception
     */
    public List<String> getFilesDates(String remotePath, String localPath) {
        List<String> stringList = new ArrayList<>();
        try {
            boolean flag = openDir(remotePath, sftp);
            if (flag) {
                //获取远端路径下所有文件
                Vector<?> vv = listFiles("*");
                if (vv == null) {
                    return null;
                } else {
                    for (Object object : vv) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                        String remoteFileName = entry.getFilename();
                        String path = localPath.substring(localPath.length() - 1).equals("/") ? localPath : localPath + "/";
                        File file = new File(path + remoteFileName);

                        //远程文件存放路径
                        InputStream inputStream = sftp.get(remotePath + remoteFileName);
                        //FileUtils.copyInputStreamToFile(inputStream, file);


                        InputStreamReader isr = new InputStreamReader(inputStream, "utf-8");
                        BufferedReader buffReader = new BufferedReader(isr);

                        String line = "";
                        StringBuilder resultStringBuilder = new StringBuilder();
                        while ((line = buffReader.readLine()) != null) {
                            // 读取每一行数据
                            resultStringBuilder.append(line).append("\n");
                            log.info("每行数据:{}", line);
                            stringList.add(line);

                        }

                        inputStream.close();
                        buffReader.close();
                    }

                }

            } else {
                log.info("对应的远程文件存放路径" + remotePath + "不存在！");
            }


        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (sftp != null) {
                if (sftp.isConnected()) {
                    sftp.disconnect();
                }
            }
            if (session != null) {
                if (session.isConnected()) {
                    session.disconnect();
                }
            }
        }
        return stringList;
    }


    /**
     * @param remotePath 远程文件存放路径  /：代表sftp设置的根目录
     * @return
     */
    public byte[] getSftpDataIO(String remotePath, String FolderName, String fileName) {
        byte[] bytes = new byte[0];

        //获取远端路径下所有文件
        try {
            remotePath = remotePath + FolderName;
            boolean flag = openDir(remotePath, sftp);
            if (flag) {
                //获取远端路径remotePath/下所有文件
                Vector<?> vv = listFiles("*");
                //log.info("目录下存在文件个数：{}",vv.size());
                if (vv == null) {
                    return null;
                } else {
                    for (Object object : vv) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                        // 文件名称带后缀 dwa_ovm_ep_city_12res_hm_2024011000.txt
                        String remoteFileNameTxt = entry.getFilename();
                        //dwa_ovm_ep_city_12res_hm_2024011000
                        String remoteFileName = remoteFileNameTxt.substring(0, remoteFileNameTxt.lastIndexOf("."));

                        //File file = new File(remotePath +"/"+ remoteFileNameTxt);

                        //log.info("文件名称(包含后缀名)：{}",remoteFileName);
                        if(remoteFileName.equals(fileName)){
                            //远程文件存放路径 /20240111/xxxxxx.txt
                            InputStream inputStream = sftp.get(remotePath +"/"+remoteFileNameTxt);
                            byte[] bytes1 = IOUtils.toByteArray(inputStream);

                            //BufferedReader buffReader = new BufferedReader(inputStreamReader);
                            ////log.info("开始读取 {} 文件数据",remoteFileName);
                            //
                            //String line = "";
                            //StringBuilder resultStringBuilder = new StringBuilder();

                            inputStream.close();
                            //buffReader.close();
                            return bytes1;
                        }

                    }
                }

            } else {
                log.info("对应的远程文件存放路径" + remotePath + "不存在！");
            }


        } catch (Exception e) {
            throw new BusinessException(ErrorType.GET_FILE_FALSE);
        }

        return bytes;
    }


    /**
     * @param remotePath 远程文件存放路径  /：代表sftp设置的根目录
     * @return
     */
    public List<String> getYdFilesDateOne(String remotePath, String FolderName,String fileName) throws IOException {

        List<String> stringList = new ArrayList<>();
        //获取远端路径下所有文件
        try {
            remotePath = remotePath + "/"+FolderName;
            boolean flag = openDir(remotePath, sftp);
            if (flag) {
                //获取远端路径remotePath/下所有文件
                Vector<?> vv = listFiles("*");
                //log.info("目录下存在文件个数：{}",vv.size());
                if (vv == null) {
                    return null;
                } else {
                    for (Object object : vv) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                        String remoteFileNameTxt = entry.getFilename();
                        String remoteFileName = remoteFileNameTxt.substring(0, remoteFileNameTxt.lastIndexOf("."));

                        //log.info("文件名称(包含后缀名)：{}",remoteFileName);
                        if(remoteFileName.equals(fileName)){
                            //远程文件存放路径 /20240111/xxxxxx.txt
                            InputStream inputStream = sftp.get(remotePath +"/"+remoteFileNameTxt);
                            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                            BufferedReader buffReader = new BufferedReader(inputStreamReader);
                            //log.info("开始读取 {} 文件数据",remoteFileName);

                            String line = "";
                            StringBuilder resultStringBuilder = new StringBuilder();

                            while ((line = buffReader.readLine()) != null) {
                                // 读取每一行数据
                                resultStringBuilder.append(line).append("\n");
                                stringList.add(line);
                            }

                            inputStream.close();
                            buffReader.close();
                        }

                    }
                }

            } else {
                log.info("对应的远程文件存放路径" + remotePath + "不存在！");
            }


        } catch (Exception e) {
            throw new BusinessException(ErrorType.GET_FILE_FALSE);
        }

        return stringList;
    }


    /**
     * 测试使用
     * @param remotePath
     * @param FolderName
     * @return
     */
    public List<String> getTest(String remotePath, String FolderName) {
        List<String> stringList = new ArrayList<>();
        //获取远端路径下所有文件
        try {
            remotePath = remotePath + "/"+ FolderName;
            boolean flag = openDir(remotePath, sftp);
            if (flag) {
                //获取远端路径remotePath/下所有文件
                Vector<?> vv = listFiles("*");
                log.info("目录下存在文件个数：{}",vv.size());
                if (vv == null) {
                    return null;
                } else {
                    for (Object object : vv) {
                        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                        // 文件名称带后缀 dwa_ovm_ep_city_12res_hm_2024011000.txt
                        String remoteFileNameTxt = entry.getFilename();
                        log.info("文件名称(包含后缀名)：{}",remoteFileNameTxt);
                        stringList = this.readFile(object,remotePath);
                        //log.info("文件数据 {}",stringList);
                    }
                }

            } else {
                log.info("对应的远程文件存放路径" + remotePath + "不存在！");
            }


        } catch (Exception e) {
            throw new BusinessException(ErrorType.GET_FILE_FALSE);
        }

        return stringList;
    }


    /**
     * @param remotePath 远程文件存放路径  /：代表sftp设置的根目录
     * @param today      当天时间
     * @return
     */
    public List<String> getYdFilesDates(String remotePath, String today) throws IOException {
        List<String> stringList = new ArrayList<>();
        //获取远端路径下所有文件
        try {
            remotePath = remotePath + today;
            boolean flag = openDir(remotePath, sftp);
            if (flag) {
                //获取远端路径remotePath/下所有文件
                Vector<?> vv = listFiles("*");
                log.info("存在文件个数：{}",vv.size());
                if (vv == null) {
                    return null;
                } else {


                    for (Object object : vv) {
                         ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                        // 文件名称
                         String remoteFileName = entry.getFilename();
                         stringList = this.readFile(object,remotePath);
                         log.info("文件数据 {}",stringList);
                         // 文件类型1
                         if(remoteFileName.contains("dwa_ovm_ep_city_12res_hm")){
                            return stringList;
                         }
                        //ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
                        //// 文件名称
                        //String remoteFileName = entry.getFilename();
                        ////log.info("文件名称(包含后缀名)：{}",remoteFileName);
                        //
                        ////远程文件存放路径 /20240111/xxxxxx.txt
                        //InputStream inputStream = sftp.get(remotePath +"/"+remoteFileName);
                        //InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
                        //BufferedReader buffReader = new BufferedReader(inputStreamReader);
                        //
                        //log.info("开始读取 {} 文件数据",remoteFileName);
                        //
                        //String line = "";
                        //StringBuilder resultStringBuilder = new StringBuilder();
                        //
                        //while ((line = buffReader.readLine()) != null) {
                        //    // 读取每一行数据
                        //    resultStringBuilder.append(line).append("\n");
                        //    stringList.add(line);
                        //}
                        //
                        //inputStream.close();
                        //buffReader.close();

                    }
                }

            } else {
                log.info("对应的远程文件存放路径" + remotePath + "不存在！");
            }


        } catch (SftpException e) {
            log.info("---------获取sftp服务器文件数据----同步失败-----");
            e.printStackTrace();
        }

        return stringList;
    }



    private List<String> readFile(Object object,String remotePath) throws IOException, SftpException {
        List<String> stringList = new ArrayList<>();
        ChannelSftp.LsEntry entry = (ChannelSftp.LsEntry) object;
        // 文件名称
        String remoteFileName = entry.getFilename();
        //log.info("文件名称(包含后缀名)：{}",remoteFileName);

        //远程文件存放路径 /20240111/xxxxxx.txt
        InputStream inputStream = sftp.get(remotePath +"/"+remoteFileName);
        InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
        BufferedReader buffReader = new BufferedReader(inputStreamReader);

        log.info("开始读取 {} 文件数据",remoteFileName);

        String line = "";
        StringBuilder resultStringBuilder = new StringBuilder();

        while ((line = buffReader.readLine()) != null) {
            // 读取每一行数据
            resultStringBuilder.append(line).append("\n");
            stringList.add(line);
        }

        inputStream.close();
        buffReader.close();

        return stringList;
    }


    //打开或者进入指定目录
    public boolean openDir(String directory, ChannelSftp sftp) {
        try {
            sftp.cd(directory);
            log.info("进入 " + directory + " 目录成功");
            return true;
        } catch (SftpException e) {
            log.info("进入 " + directory + " 目录失败");
            return false;
        }
    }

    //返回目录下所有文件信息
    public Vector listFiles(String directory) throws SftpException {
        return sftp.ls(directory);
    }

    /**
     * 断开与主机的连接
     */
    public void disconnect() {
        try {
            sftp.disconnect();
        } catch (Exception ignored) {
        }
        try {
            channel.disconnect();
        } catch (Exception ignored) {
        }
        try {
            session.disconnect();
        } catch (Exception ignored) {
        }
    }

    /**
     * 得到SFTP实例
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @return
     * @throws Exception
     */
    public static SftpClientUtil getInstans(String host, String username, String password, int port) throws Exception {
        return new SftpClientUtil(host, username, password, port, false);
    }

    /**
     * 得到SFTP实例
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @param encoding 字符集编码
     * @return
     * @throws Exception
     */
    public static SftpClientUtil getInstans(String host, String username, String password, int port, String encoding)
            throws Exception {
        return new SftpClientUtil(host, username, password, port, encoding);
    }

    /**
     * 得到SFTP实例
     *
     * @param host     主机
     * @param username 用户名
     * @param password 密码
     * @param port     端口
     * @param encoding 字符集编码
     * @param timeout  超时时间
     * @return
     * @throws Exception
     */
    public static SftpClientUtil getInstans(String host, String username, String password, int port, String encoding,
                                            int timeout) throws Exception {
        return new SftpClientUtil(host, username, password, port, encoding, timeout);
    }



}
